

******************************************************************************* ;
*****PROGRAM TO PULL IN TRADE DATA AND MAKE FIRM-BY-COUNTRY-HS PRODUCT DATASET ;

**This simplified version only uses the LFTTD;
**Should be better across time;
******************************************************************************* ;

****written by TFP      ;
****written on 12-04-18 ;


options obs=max;
*options obs=100000 ; 
    
*debugging;
libname input 'xxxx/input' ;
libname output "xxxx/data";

%let output=xxxx/data ;
%let ver=_c201601;

 %include 'yyyy/pdata.sas' ;

/*


*Raw census files ;
 %include '/projects/lib/sas/pdata.sas' ;


*Pull in import and export data;
 
%let list_imp=firmid type related ;
%let list_exp=firmid related; 

%macro pull_trade(y,trans) ;
   data &trans.orts&y ;
      %if &trans = imp %then %do;
	set pdata.&trans._comb&y.&ver(keep=&&list_&trans  importer value country hs rename=(value=&trans._value)) ;
      %end;
      %else %do;
        set pdata.&trans._comb&y.&ver(keep=&&list_&trans value country hs rename=(value=&trans._value)) ;
      %end;

      *Limit imports by type ;
       %if &trans=imp %then %do ;
         if type in ('1','2','5'); 

	  %end; /*end imports only */


      *Make rp trade variable ; 
       if related="Y" then rp_&trans._value=&trans._value ;

     *identify unmatched trade;
      if firmid="" then firmid="unmatched" ;
   run;



  *Aggregate to product-country-firm level ;
    proc sort data=&trans.orts&y; by firmid country hs ; 
    proc means sum noprint data=&trans.orts&y;
      by firmid country hs ; 
      var &trans._value rp_&trans._value ;
      output out=&trans.orts&y._agg(drop=_type_ rename=(_freq_=trans_count)) sum(&trans._value rp_&trans._value)=;
     run;

 *Output dataset to merge to firm panel ;
   proc export data=&trans.orts&y._agg
    outfile="&output/&trans.orts&y._lfttd.dta"
    dbms=dta replace;
    run;



  %mend;

  %pull_trade(2007,imp); 
  %pull_trade(2007,exp); 


